<template>
  <div>
    <div class="pageTitleWhole">
      <a-breadcrumb>
        <a-breadcrumb-item>限价管理</a-breadcrumb-item>
      </a-breadcrumb>
    </div>
    <div class="pageContentWhole">
      <a-form layout="inline">
        <a-form-item label="航线">
          <a-select v-model="searchForm.routeName" class="selectWidth">
            <a-select-option value>全部</a-select-option>
            <a-select-option value="华南线">华南线</a-select-option>
            <a-select-option value="东南线">东南线</a-select-option>
            <a-select-option value="西南线">西南线</a-select-option>
            <a-select-option value="东北线">东北线</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="港口">
          <a-select
            show-search
            allowClear
            v-model="searchForm.portId"
            :show-arrow="false"
            :filter-option="false"
            :default-active-first-option="false"
            :not-found-content="null"
            @search="value => handlePortNameChange(value)"
            @select="emptyChange"
            class="selectInputWidth"
          >
            <a-select-option v-for="d in portList" :key="d.id">{{ d.name }}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="海船公司">
          <a-select
            show-search
            allowClear
            v-model="searchForm.payShipId"
            :show-arrow="false"
            :filter-option="false"
            :default-active-first-option="false"
            :not-found-content="null"
            @search="value => handlePayShipChange(value)"
            @select="emptyChangePayShip"
            class="selectInputWidth"
          >
            <a-select-option v-for="(v) in payList" :key="v.id">{{v.name}}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="状态">
          <a-select v-model="searchForm.status" class="selectWidth">
            <a-select-option value>全部</a-select-option>
            <a-select-option :value="1">正常</a-select-option>
            <a-select-option :value="0">冻结</a-select-option>
          </a-select>
        </a-form-item>

        <a-form-item>
          <a-button type="primary" @click="handleSubmit1">查询</a-button>
        </a-form-item>
        <a-form-item>
          <a-button type="primary" @click="exportExcel">导出excel</a-button>
        </a-form-item>
        <a-form-item>
          <a-button type="primary" @click="addItem">添加限价</a-button>
        </a-form-item>
      </a-form>

      <a-table
        bordered
        :columns="columns"
        :data-source="tableData"
        class="tableMargin"
        :pagination="pagination"
        :rowKey="(r, i) => i"
        :scroll="{x:1450}"
      >
        <template slot="rn" slot-scope="text, record, index">{{index + 1}}</template>
        <template slot="operation" slot-scope="text, record">
          <a @click="editIt(record)">编辑</a>
          <a
            @click="freezeIt(record.id, record.status)"
          >{{record.status === 1 ? '冻结': (record.status === 0 ? '恢复':'')}}</a>
        </template>
      </a-table>
    </div>

    <!-- 新增/编辑限价 -->
    <a-modal
      :visible="visible"
      :title="titleStr"
      centered
      destroyOnClose
      :maskClosable="false"
      :confirmLoading="confirmLoading"
      @ok="handleOk"
      @cancel="handleCancel"
    >
      <a-form-model
        ref="rulesForm"
        :model="form"
        :rules="rulesStr"
        :labelCol="{span: 5}"
        :wrapperCol="{span: 16}"
      >
        <a-form-model-item label="航线" prop="routeName">
          <a-select v-if="isAdd" v-model="form.routeName">
            <a-select-option value>请选择</a-select-option>
            <a-select-option value="华南线">华南线</a-select-option>
            <a-select-option value="东南线">东南线</a-select-option>
            <a-select-option value="西南线">西南线</a-select-option>
            <a-select-option value="东北线">东北线</a-select-option>
          </a-select>
          <span v-if="!isAdd">{{form.routeName}}</span>
        </a-form-model-item>
        <a-form-model-item label="港口1" prop="portId1">
          <a-select
            v-if="isAdd"
            show-search
            v-model="form.portId1"
            :show-arrow="false"
            :filter-option="false"
            :default-active-first-option="false"
            :not-found-content="null"
            @search="value => handlePortNameChange1(value)"
            @select="emptyChange(1)"
          >
            <a-select-option v-for="d in portList1" :key="d.id">{{ d.name }}</a-select-option>
          </a-select>
          <span v-if="!isAdd">{{form.payableShipName}}</span>
        </a-form-model-item>
        <a-form-model-item label="港口2" prop="portId2">
          <a-select
            v-if="isAdd"
            show-search
            v-model="form.portId2"
            :show-arrow="false"
            :filter-option="false"
            :default-active-first-option="false"
            :not-found-content="null"
            @search="value => handlePortNameChange2(value)"
            @select="emptyChange(2)"
          >
            <a-select-option v-for="d in portList2" :key="d.id">{{ d.name }}</a-select-option>
          </a-select>
          <span v-if="!isAdd">{{form.portName1}}</span>
        </a-form-model-item>
        <a-form-model-item label="箱型" prop="containerTypeId">
          <a-select v-if="isAdd" v-model="form.containerTypeId">
            <a-select-option value>请选择</a-select-option>
            <a-select-option
              v-for="(item,index) in containerList"
              :key="index"
              :value="item.id"
            >{{item.name}}</a-select-option>
          </a-select>
          <span v-if="!isAdd">{{form.portName2}}</span>
        </a-form-model-item>
        <a-form-model-item label="海船公司" prop="payShipId">
          <a-select
            v-if="isAdd"
            show-search
            v-model="form.payShipId"
            :show-arrow="false"
            :filter-option="false"
            :default-active-first-option="false"
            :not-found-content="null"
            @search="value => handlePayShipChange1(value)"
            @select="emptyChangePayShip1"
          >
            <a-select-option v-for="(v) in payList1" :key="v.id">{{v.name}}</a-select-option>
          </a-select>
          <span v-if="!isAdd">{{form.payableShipName}}</span>
        </a-form-model-item>

        <br />
        <div style="border: 1px solid #dcdcdc; padding-top: 20px; position: relative;">
          <span
            style="position: absolute; top: -12px; left: 20px; background: white;padding: 0 7px;"
          >时间价格一</span>
          <a-form-model-item label="装货时间" prop="startLoadingTime1">
            <a-range-picker
              :show-time="{ format: 'HH:mm' }"
              format="YYYY-MM-DD HH:mm"
              :value="form.loadingTime1"
              @change="onDateChange1"
            >
              <a-icon slot="suffixIcon" type="calendar" />
            </a-range-picker>
          </a-form-model-item>
          <a-form-model-item label="价格（元）" prop="price1">
            <a-input-number
              v-model="form.price1"
              :min="0.01"
              :max="999999999999.99"
              :precision="2"
              class="selectInputWidth"
            ></a-input-number>
          </a-form-model-item>
        </div>
        <br />

        <div style="border: 1px solid #dcdcdc; padding-top: 20px; position: relative;">
          <span
            style="position: absolute; top: -12px; left: 20px; background: white;padding: 0 7px;"
          >时间价格二</span>
          <a-form-model-item label="装货时间" prop="startLoadingTime2">
            <a-range-picker
              :show-time="{ format: 'HH:mm' }"
              format="YYYY-MM-DD HH:mm"
              :value="form.loadingTime2"
              @change="onDateChange2"
            >
              <a-icon slot="suffixIcon" type="calendar" />
            </a-range-picker>
          </a-form-model-item>
          <a-form-model-item label="价格（元）" prop="price2">
            <a-input-number
              v-model="form.price2"
              :min="0.01"
              :max="999999999999.99"
              :precision="2"
              class="selectInputWidth"
            ></a-input-number>
          </a-form-model-item>
        </div>
      </a-form-model>
    </a-modal>
  </div>
</template>

<script>
import debounce from 'lodash/debounce'
import moment from 'moment'
import {
  queryCustNameList,
  queryPortNameList,
  queryContainerTypeList
} from '@/api/salesCenter'
import { commonExport } from '@/api/request'
import { queryPriceLimitList, addPriceLimit, editPriceLimit } from '@/api/orderCenter'

const fomrMessage = `必填项不能为空`
const defaultForm = () => ({
  routeName: '', // 路线
  portId1: '', // 港口1id
  portId2: '', // 港口2id
  containerTypeId: '', // 箱型
  payShipId: '',
  startLoadingTime1: '', // 装货时间1
  endLoadingTime1: '', // 装货时间1
  price1: '', // 价格1
  startLoadingTime2: '', // 装货时间2
  endLoadingTime2: '', // 装货时间2
  price2: '', // 价格2
  loadingTime1: [null, null],
  loadingTime2: [null, null]
})

export default {
  data () {
    this.handlePortNameChange = debounce(this.handlePortNameChange, 800)
    this.handlePayShipChange = debounce(this.handlePayShipChange, 800)
    // modal
    this.handlePayShipChange1 = debounce(this.handlePayShipChange1, 800)
    this.handlePortNameChange1 = debounce(this.handlePortNameChange1, 800)
    this.handlePortNameChange2 = debounce(this.handlePortNameChange2, 800)

    const columns = [
      {
        title: '序号',
        width: '75px',
        scopedSlots: { customRender: 'rn' }
      },
      {
        title: '航线',
        width: '100px',
        dataIndex: 'routeName'
      },
      {
        title: '港口1',
        dataIndex: 'portName1'
      },
      {
        title: '港口2',
        dataIndex: 'portName2'
      },
      {
        title: '箱型',
        width: 90,
        dataIndex: 'containerType'
      },
      {
        title: '海船公司',
        dataIndex: 'payableShipName'
      },
      {
        title: '价格一',
        children: [
          {
            title: '装货时间',
            width: 160,
            customRender: (text, record) => {
              return `${record.startLoadingTime1}~${record.endLoadingTime1}`
            }
          },
          {
            title: '价格(元)',
            dataIndex: 'price1'
          }
        ]
      },
      {
        title: '价格二',
        children: [
          {
            title: '装货时间',
            width: 160,
            customRender: (text, record) => {
              return `${record.startLoadingTime2}~${record.endLoadingTime2}`
            }
          },
          {
            title: '价格(元)',
            dataIndex: 'price2'
          }
        ]
      },
      {
        title: '状态',
        dataIndex: 'status',
        width: 90,
        customRender: (text, row, index) => {
          if (text === 1) {
            return <a-badge status="success" text="正常" />
          } else if (text === 0) {
            return <a-badge status="error" text="冻结" />
          }
        },
        _needName: true
      },
      {
        title: '操作',
        width: 115,
        fixed: 'right',
        scopedSlots: { customRender: 'operation' }
      }
    ]

    return {
      loading: false,
      searchForm: {
        routeName: '',
        portId: null,
        payShipId: '',
        status: ''
      },
      portList: [],
      payList: [],
      columns,
      tableData: [],
      pagination: {},
      pageNum: 1,
      pageSize: 10,
      // modal
      isAdd: true,
      confirmLoading: false,
      visible: false,
      form: defaultForm(),
      portList1: [],
      portList2: [],
      payList1: [],
      containerList: [],
      rules: {
        routeName: [{ required: true, message: fomrMessage, trigger: ['blur', 'change'] }],
        portId1: [{ required: true, message: fomrMessage, trigger: ['blur', 'change'] }],
        portId2: [{ required: true, message: fomrMessage, trigger: ['blur', 'change'] }],
        containerTypeId: [{ required: true, message: fomrMessage, trigger: ['blur', 'change'] }],
        payShipId: [{ required: true, message: fomrMessage, trigger: ['blur', 'change'] }],
        startLoadingTime1: [{ required: true, message: fomrMessage, trigger: ['blur', 'change'] }],
        startLoadingTime2: [{ required: true, message: fomrMessage, trigger: ['blur', 'change'] }],
        price1: [{ required: true, message: fomrMessage, trigger: ['blur', 'change'] }],
        price2: [{ required: true, message: fomrMessage, trigger: ['blur', 'change'] }]
      },
      rules2: {
        startLoadingTime1: [{ required: true, message: fomrMessage, trigger: ['blur', 'change'] }],
        startLoadingTime2: [{ required: true, message: fomrMessage, trigger: ['blur', 'change'] }],
        price1: [{ required: true, message: fomrMessage, trigger: ['blur', 'change'] }],
        price2: [{ required: true, message: fomrMessage, trigger: ['blur', 'change'] }]
      }
    }
  },
  computed: {
    titleStr () {
      return this.isAdd ? '新增限价' : '编辑限价'
    },
    rulesStr () {
      return this.isAdd ? this.rules : this.rules2
    }
  },
  methods: {
    handlePayShipChange (nameLike = '') {
      queryCustNameList({
        nameLike,
        belongCompany: 'JIA_HUA',
        custTypeLike: 'SUPPLIER',
        isPayable: 1
      }).then(res => {
        this.payList = res.data
      }).catch(rs => { })
    },
    emptyChangePayShip () {
      this.handlePayShipChange()
    },
    handlePayShipChange1 (nameLike = '') {
      queryCustNameList({
        nameLike,
        belongCompany: 'JIA_HUA',
        custTypeLike: 'SUPPLIER',
        isPayable: 1
      }).then(res => {
        this.payList1 = res.data
      }).catch(rs => { })
    },
    emptyChangePayShip1 () {
      this.handlePayShipChange1()
    },
    handlePortNameChange (nameLike = '') {
      queryPortNameList({
        nameLike,
        status: 1
      }).then(res => {
        this.portList = res.data
      })
    },
    containerListRequest (e) {
      queryContainerTypeList(e)
        .then(res => {
          this.containerList = res.data
        })
        .catch(rs => { })
    },
    emptyChange (n) {
      if (n === 1) this.handlePortNameChange1()
      else if (n === 2) this.handlePortNameChange2()
      else this.handlePortNameChange()
    },
    handlePortNameChange1 (nameLike = '') {
      queryPortNameList({
        nameLike,
        status: 1
      }).then(res => {
        this.portList1 = res.data
      })
    },
    handlePortNameChange2 (nameLike = '') {
      queryPortNameList({
        nameLike,
        status: 1
      }).then(res => {
        this.portList2 = res.data
      })
    },
    handleSubmit1 () {
      this.pageNum = 1
      this.handleSubmit()
    },
    handleSubmit () {
      queryPriceLimitList({
        ...this.searchForm,
        pageNum: this.pageNum,
        pageSize: this.pageSize
      }).then(rsp => {
        this.tableData = rsp.data.list
        this.pagination = {
          current: this.pageNum,
          pageSize: rsp.data.pageSize,
          total: rsp.data.total,
          showQuickJumper: false,
          showSizeChanger: true,
          showTotal: total => `共${total}条记录 第${this.pageNum}/${rsp.data.pages}页`,
          onChange: pageNum => {
            this.pageNum = pageNum
            this.handleSubmit()
          },
          onShowSizeChange: (current, size) => {
            this.pageNum = current
            this.pageSize = size
            this.handleSubmit()
          }
        }
      })
    },
    exportExcel () {
      commonExport('/order/exportPriceLimitList', {
        ...this.searchForm,
        pageNum: this.pageNum,
        pageSize: this.pageSize,
        columns: [
          {
            title: '航线',
            dataIndex: 'routeName'
          },
          {
            title: '港口1',
            dataIndex: 'portName1'
          },
          {
            title: '港口2',
            dataIndex: 'portName2'
          },
          {
            title: '箱型',
            dataIndex: 'containerType'
          },
          {
            title: '海船公司',
            dataIndex: 'payableShipName'
          },
          {
            title: '价格一-装货时间',
            dataIndex: 'loadingTime1'
          },
          {
            title: '价格一-价格(元)',
            dataIndex: 'price1'
          },
          {
            title: '价格二-装货时间',
            dataIndex: 'loadingTime2'
          },
          {
            title: '价格二-价格(元)',
            dataIndex: 'price2'
          },
          {
            title: '状态',
            dataIndex: 'statusName'
          }]
      })
    },
    freezeIt (id, isFrozen) {
      if (!this.$root._bc.frozen) {
        this.$message.error('您无此权限！')
        return
      }
      let text = '确定冻结吗？'
      let successText = '冻结成功！'
      if (isFrozen === 0) {
        text = '确定恢复正常吗？'
        successText = '恢复成功！'
      }

      let _this = this
      this.$confirm({
        title: text,
        okType: 'danger',
        onOk () {
          editPriceLimit({ id, status: 1 - isFrozen }).then(rsp => {
            _this.$message.success(successText)
            _this.handleSubmit()
          })
        }
      })
    },
    // modal
    onDateChange1 (date, dataStr) {
      this.form.startLoadingTime1 = dataStr[0]
      this.form.endLoadingTime1 = dataStr[1]
      this.form.loadingTime1 = [date[0], date[1]]
    },
    onDateChange2 (date, dataStr) {
      this.form.startLoadingTime2 = dataStr[0]
      this.form.endLoadingTime2 = dataStr[1]
      this.form.loadingTime2 = [date[0], date[1]]
    },
    addItem () {
      if (!this.$root._bc.add) {
        this.$message.error('您无此权限！')
        return
      }
      this.form = defaultForm()
      this.emptyChange(1)
      this.emptyChange(2)
      this.containerListRequest({})
      this.emptyChangePayShip1()
      this.isAdd = true
      this.visible = true
    },
    editIt (record) {
      if (!this.$root._bc.edit) {
        this.$message.error('您无此权限！')
        return
      }
      this.form = { ...record }
      this.form.loadingTime1 = [moment(record.startLoadingTime1), moment(record.endLoadingTime1)]
      this.form.loadingTime2 = [moment(record.startLoadingTime2), moment(record.endLoadingTime2)]
      this.isAdd = false
      this.visible = true
    },
    handleOk () {
      this.$refs.rulesForm.validate(valid => {
        if (valid) {
          // 港口1和港口2不可重复
          if (this.form.portId1 && (this.form.portId1 === this.form.portId2)) {
            this.$message.error('港口1和港口2不可重复')
            return false
          }

          this.confirmLoading = true
          if (this.isAdd) {
            addPriceLimit({ ...this.form }).then(rsp => {
              this.$message.success('新增成功')
              this.visible = false
              this.handleSubmit()
              setTimeout(() => { this.confirmLoading = false }, 1000)
            }).catch(e => { this.confirmLoading = false })
          } else {
            editPriceLimit({ ...this.form }).then(rsp => {
              this.$message.success('编辑成功')
              this.visible = false
              this.handleSubmit()
              setTimeout(() => { this.confirmLoading = false }, 1000)
            }).catch(e => { this.confirmLoading = false })
          }
        }
      })
    },
    handleCancel () {
      this.$refs.rulesForm.resetFields()
      this.visible = false
    }
  },
  mounted () {
    this.emptyChange()
    this.emptyChangePayShip()
    this.handleSubmit()
  }
}
</script>
